﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;

namespace MatlabIG
{
    class Object3DGrid : Object3D
    {
        BasicEffect basicEffect;
        VertexBuffer vertexbuffer;
        int totalLinesCount = 0;

        public void Init(float x, float y, float raster, Color color)
        {
            List<VertexPositionColor> verts = new List<VertexPositionColor>();
            // fill vetices buffer    
            // 1. horizontal
            for (float j = -y / 2; j <= y / 2; j += raster)
            {
                VertexPositionColor v = new VertexPositionColor(new Vector3(-x / 2, j, 0), color);
                verts.Add(v);
                v = new VertexPositionColor(new Vector3(x / 2, j, 0), color);
                verts.Add(v);
            }
            // 2. vertical
            for (float i = -x / 2; i <= x / 2; i += raster)
            {
                VertexPositionColor v = new VertexPositionColor(new Vector3(i, -y/2, 0), color);
                verts.Add(v);
                v = new VertexPositionColor(new Vector3(i, y/2, 0), color);
                verts.Add(v);
            }
            VertexPositionColor[] vertices = verts.ToArray();
            vertexbuffer = new VertexBuffer(Globals.Graphics.GraphicsDevice, typeof(VertexPositionColor), vertices.Length, BufferUsage.None);
            vertexbuffer.SetData(vertices);
            totalLinesCount = vertices.Length / 2;

            // init basic effect
            basicEffect = new BasicEffect(Globals.Graphics.GraphicsDevice);
        }

        public void Draw()
        {
            // set effect parameters
            basicEffect.World = Matrix.Identity;
            basicEffect.View = Globals.ViewMat;
            basicEffect.Projection = Globals.ProjectionMat;
            basicEffect.LightingEnabled = false;

            foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes)
            {
                pass.Apply();
                Globals.Graphics.GraphicsDevice.SetVertexBuffer(vertexbuffer);
                Globals.Graphics.GraphicsDevice.DrawPrimitives(PrimitiveType.LineList, 0, totalLinesCount);
            }
        }
    }
}
